import { login } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: localStorage.getItem('userName'),
    avatar: '@/assets/avatar.png'
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  }
}

const actions = {
  // user login
  async login({ commit }, userInfo) {
    const { data } = await login(userInfo)
    console.log(data)
    commit('SET_TOKEN', data.token.token)
    setToken(data.token.token)
    commit('SET_NAME', data.user.name)
    commit('SET_AVATAR', data.user.avatar)
    localStorage.setItem('userName', data.user.name)
  },

  // user logout
  logout({ commit }) {
    removeToken() // must remove  token  first
    // 重置路由
    resetRouter()
    commit('RESET_STATE')
  },

  // remove token
  resetToken({ commit }) {
    removeToken() // must remove  token  first
    commit('RESET_STATE')
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

